<template>
	<wd-popup v-model="show" position="bottom" custom-style="border-radius:32rpx 32rpx 0 0;" safe-area-inset-bottom>
		<!-- 选择楼盘 -->
		<view class="select-property">
			<wd-search v-model="searchValue" placeholder="请输入要搜索的楼盘名称" cancel-txt="搜索" @cancel="handleSearch" />
			<wd-picker-view v-if="columns.length" v-model="selectValue" :columns="formattedColumns" :loading="loading"
				label-key="title" value-key="id" />
			<wd-status-tip v-else image="search" tip="当前搜索无结果" />
			<wd-button v-if="columns.length" block custom-style="margin: 0 32rpx;" @click="handleConfirm">确定</wd-button>
		</view>
	</wd-popup>
</template>

<script setup>
	import {
		ref, computed
	} from 'vue'
	import request from "@/utils/request.js";

	// emits
	const emits = defineEmits(['confirm'])
	// 显示
	const show = ref(false)
	// 搜索值
	const searchValue = ref('')
	// 选择值
	const selectValue = ref()
	// columns
	const columns = ref([])
	// 加载状态
	const loading = ref(false)
	// 处理搜索
	const handleSearch = () => {
		if (!searchValue.value) return
		loading.value = true
		const params = {
			keyword: searchValue.value,
			pageIndex: 1
		}
		request.get('/fenxiao/property/search-property-list-by-keyword', params).then(data => {
			data = JSON.parse(data)
			columns.value = data.data
			selectValue.value = columns.value[0]?.id || ''
		}).catch((error) => {
			uni.showToast({
				title: error,
				icon: 'error'
			})
		}).finally(() => {
			loading.value = false
		})
	}
	// 处理确定
	const handleConfirm = () => {
		uni.showLoading({
			mask: true
		})
		const obj = columns.value.find(item => item.id === selectValue.value) || {}
		const adcode = obj.adcode.toString()
		const params = {
			name: obj.title,
			address: obj.address,
			longitude: obj.location.lng,
			latitude: obj.location.lat,
			provinceCode: `${adcode.substring(0, 2)}0000`,
			cityCode: `${adcode.substring(0, 4)}00`,
			areaCode: adcode,
		}
		request.post('/fenxiao/property/create', params).then(data => {
			emits('confirm', data)
			show.value = false
		}).catch((error) => {
			setTimeout(() => {
				uni.showToast({
					title: error,
					icon: 'error'
				})
			})
		}).finally(() => {
			uni.hideLoading()
		})
	}
	// 打开
	const open = () => {
		show.value = true
	}

	defineExpose({
		open
	})
	const formattedColumns = computed(() => {
	  return columns.value.map((item) => {
	    return {
			...item,
	      title: `${item.title} <span style="color: #999;font-size: 14px;">${item.address}</span>`,
	    };
	  });
	});
</script>

<style lang="scss">
	// 选择楼盘
	.select-property {
		padding: 16rpx 0;
	}
</style>